﻿
using DotNetOpenMail;
using DotNetOpenMail.SmtpAuth;
using IScheduler.Core.Properties;

namespace IScheduler.Core.Services
{
    public class SmtpMailer : Mailer
    {

        /// <summary>
        /// Send email to distribution list.
        /// </summary>
        public override void Send()
        {
            EmailMessage msg = new EmailMessage();

            foreach (string addr in AddressesFromList(To))
            {
                msg.AddToAddress(addr);
            }

            msg.FromAddress = new EmailAddress(From);

            msg.Subject = Subject;

            if (TextBody != null) msg.TextPart = new TextAttachment(TextBody);
            if (HtmlBody != null) msg.HtmlPart = new HtmlAttachment(HtmlBody);

            SmtpServer server = new SmtpServer(SmtpHost, SmtpServerPort);

            switch (SmtpAuthType)
            {
                case "BASIC":
                    LoggingService.Info(Resources.SmtpMailerInfoAuthenticationMode);
                    SmtpAuthToken at = new SmtpAuthToken(SmtpAuthUsername, SmtpAuthPassword);
                    server.SmtpAuthToken = at;
                    break;
                default:
                    // no authentication
                    break;
            }



            LoggingService.Info(string.Format("Sending mail to {0} from {1} with subject {2}", msg.ToAddresses, msg.FromAddress, msg.Subject));

            msg.Send(server);

            LoggingService.Info("Sent mail");

           
        }

        /// <summary>
        /// Return Addresses email.
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        string[] AddressesFromList(string list)
        {
            return list.Split(';');
        }


    }
}
